package cn.player.download;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;

import cn.player.AIDLDownloadClient;
import cn.player.AIDLDownloadService;
import cn.player.entity.VideoBean;
import cntv.player.core.util.LogUtil;

/**
 * Created by xingliao_zgl on 16/7/8.
 */
public class DownloadManager {

    private static DownloadManager mDownloadManager;
    private CallBack mCallBack;
    private DownloadConfiguration mConfig;

    private DownloadManager() {
    }

    public static DownloadManager getInstance() {
        if (mDownloadManager == null) {
            synchronized (DownloadManager.class) {
                mDownloadManager = new DownloadManager();
            }
        }
        return mDownloadManager;
    }

    public void init(Context context) {
        init(context, new DownloadConfiguration(context));
    }

    public void init(Context context, DownloadConfiguration downloadConfigration) {
        mConfig = downloadConfigration;
        mServiceIntent = new Intent(context, FileDownloadService.class);
        context.startService(mServiceIntent);
        context.bindService(mServiceIntent, mRemoteService, Context.BIND_AUTO_CREATE);
    }


    public void releaseDownloader(Context context) {
        try {
            if (mAidlService != null) {
                mAidlService.setClientIMPL(null);
                context.unbindService(mRemoteService);
            }
            if (mServiceIntent != null) {
                context.stopService(mServiceIntent);
            }
            mCallBack = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void startDownload(VideoBean videoBean) {
        startDownload(videoBean, 0, null);
    }

    public void startDownload(VideoBean videoBean, int priority) {
        startDownload(videoBean, priority, null);
    }


    /**
     * 开始任务下载,
     *
     * @param videoBean
     * @param priority  任务优先级,越大越优先执行
     * @param callBack
     */
    public void startDownload(VideoBean videoBean, int priority, CallBack callBack) {
        this.mCallBack = callBack;

        DownloadInfo downloadInfo = new DownloadInfo();
        downloadInfo.setVid(videoBean.getId() + "");
        String requestUrl = videoBean.getQiniu_m3u8_video_url();
        downloadInfo.setRequestUrl(requestUrl);
        downloadInfo.setFilename(requestUrl.substring(requestUrl.lastIndexOf("/") + 1));
        downloadInfo.setTargetFilePath(mConfig.getCacheFilePath() + "/" + downloadInfo.getVid() + "/");
        try {
            mAidlService.addNewTask(downloadInfo, priority);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private Intent mServiceIntent;
    private AIDLDownloadService mAidlService;

    ServiceConnection mRemoteService = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            mAidlService = AIDLDownloadService.Stub.asInterface(iBinder);
            try {
                mAidlService.setClientIMPL(mAidlClient);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mAidlService = null;
        }
    };

    private AIDLDownloadClient mAidlClient = new AIDLDownloadClient.Stub() {
        @Override
        public void onTaskStart(DownloadInfo entity) throws RemoteException {
//            LogUtil.u("开始下载,filename = " + entity.getFilename());
            if (mCallBack != null) {
                mCallBack.onDownloadStarted(entity);
            }
        }

        @Override
        public void onTaskUpdate(DownloadInfo entity) throws RemoteException {
            if (mCallBack != null) {
                mCallBack.onDownloadUpdate(entity);
            }
        }

        @Override
        public void onTaskComplete(DownloadInfo entity) throws RemoteException {
            if (mCallBack != null) {
                mCallBack.onDownloadCompleted(entity);
            }
//            LogUtil.u("下载完成,filename = " + entity.getFilename());
//            FileCache mFileCache = new FileCache(mConfig.generateCacheFile(entity.getFilename()),mConfig.getLruDiskCache());
//            mFileCache.close();
        }

        @Override
        public void onTaskPaused(DownloadInfo entity) throws RemoteException {
            if (mCallBack != null) {
                mCallBack.onDownloadPaused(entity);
            }
        }

        @Override
        public void onTaskCanceled(DownloadInfo entity) throws RemoteException {
            if (mCallBack != null) {
                mCallBack.onDownloadCanceled(entity);
            }
        }

        @Override
        public void onTaskFailed(DownloadInfo entity, String err) throws RemoteException {
            LogUtil.e("zl", "下载失败,filename = " + entity.getFilename());
            if (mCallBack != null) {
                mCallBack.onDownloadFailed(err);
            }
        }

        @Override
        public void onNoTasks() throws RemoteException {

        }
    };

}
